package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;

import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;

import org.apache.dubbo.config.annotation.DubboReference;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private AnnouncementApi announcementApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private VideoApi videoApi;

    /**
     * 根据环信id查询用户详情
     */
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        //1、根据环信id查询用户
        User user = userApi.findByHuanxin(huanxinId);
        //2、根据用户id查询用户详情
        UserInfo userInfo = userInfoApi.findById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //添加好友关系
    public void contacts(Long friendId) {
        //1、将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + friendId);
        if(!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
        //2、如果注册成功，记录好友关系到mongodb
        friendApi.save(UserHolder.getUserId(),friendId);
    }

    //分页查询联系人列表
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //1、调用API查询当前用户的好友数据 -- List<Friend>
        List<Friend> list = friendApi.findByUserId(UserHolder.getUserId(),page,pagesize);
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //2、提取数据列表中的好友id
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //3、调用UserInfoAPI查询好友的用户详情
        UserInfo info = new UserInfo();
        info.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
        //4、构造VO对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if(userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0l,vos);
    }

    //喜欢列表
    public PageResult loves(Integer page, Integer pagesize) {
        PageResult p = new PageResult();
        List<LovesVo> vos = new ArrayList<>();

        //获取当前登录用户id
        Long userId = UserHolder.getUserId();
        //查询用户发布的动态
        List<Comment> commentList = commentApi.select(userId, 3, page, pagesize);
        if (commentList.size() <= 0 || commentList == null){
            //当前用户么有发布过动态
            p.setPagesize(pagesize);
            p.setPage(page);
            p.setCounts(0l);
            p.setItems(new ArrayList<>());
            p.setPages(1l);
            return p;
        }

        //获取评论人id
        Set<Long> set = new HashSet<>();
        for (Comment comment : commentList) {
            set.add(comment.getUserId());
        }
        List<Long> loveList = new ArrayList<>(set);

        //查询详细信息
        Map<Long, UserInfo> ids = userInfoApi.findByIds(loveList, null);
        LovesVo vo = null;
        for (Comment comment : commentList) {
            UserInfo userInfo = ids.get(comment.getUserId());
            if (userInfo != null){
                vo = new LovesVo();
                vo.setId(userInfo.getId() + "");
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd kk:mm:ss").format(new Date(comment.getCreated())));
                vos.add(vo);
            }
        }
        p.setPage(page);
        p.setPagesize(pagesize);
        p.setCounts(Long.valueOf(vos.size()));
        p.setPages(Long.valueOf(vos.size() / pagesize));
        p.setItems(vos);
        return p;
    }

    //点赞列表
    //现在的id就是当前用户的id, 值是点赞人的id
    public PageResult likes(Integer page, Integer pagesize) {
        PageResult p = new PageResult();
        List<LovesVo> vos = new ArrayList<>();

        //获取当前登录用户id
        Long userId = UserHolder.getUserId();

        Set<Long> set = new HashSet<>();

        //查询视频点赞人id
        BoundSetOperations keys = redisTemplate.boundSetOps("sppl" + userId);
        if (keys != null && keys.size() > 0){
            Set<Long> set2 = keys.members();
            for (Long key : set2) {
                set.add(key);
            }
        }

        //查询用户发布的动态
        List<Comment> commentList = commentApi.select(userId, 1, page, pagesize);
        if ( commentList != null && commentList.size() > 0){
            //获取评论人id
            for (Comment comment : commentList) {
                set.add(comment.getUserId());
            }
        }

        if (set == null || set.size() <= 0){
            p.setPagesize(pagesize);
            p.setPage(page);
            p.setCounts(0l);
            p.setItems(new ArrayList<>());
            p.setPages(1l);
        }

        //查询详细信息
        List<Long> likeList = new ArrayList<>(set);
        Map<Long, UserInfo> ids = userInfoApi.findByIds(likeList, null);
        LovesVo vo = null;
        for (Comment comment : commentList) {
            UserInfo userInfo = ids.get(comment.getUserId());
            if (userInfo != null){
                vo = new LovesVo();
                vo.setId(userInfo.getId() + "");
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd kk:mm:ss").format(new Date(comment.getCreated())));
                vos.add(vo);
            }
        }
        p.setPage(page);
        p.setPagesize(pagesize);
        p.setCounts(Long.valueOf(vos.size()));
        p.setPages(Long.valueOf(vos.size() / pagesize));
        p.setItems(vos);
        return p;
    }

    //评论列表
    public PageResult comments(Integer page, Integer pagesize) {
        PageResult p = new PageResult();
        List<LovesVo> vos = new ArrayList<>();

        //获取当前登录用户id
        Long userId = UserHolder.getUserId();

        Set<Long> set = new HashSet<>();
        //查询动态评论
        List<Comment> commentList = commentApi.select(userId, 1, page, pagesize);
        if (commentList != null && commentList.size() > 0) {
            //获取评论人id
            for (Comment comment : commentList) {
                set.add(comment.getUserId());
            }
        }

        //查询视频评论
        BoundSetOperations keys = redisTemplate.boundSetOps("sppl" + userId);
        if (keys != null && keys.size() > 0){
            Set<Long> set2 = keys.members();
            for (Long key : set2) {
                set.add(key);
            }
        }

        if (set == null || set.size() <= 0){
            p.setPagesize(pagesize);
            p.setPage(page);
            p.setCounts(0l);
            p.setItems(new ArrayList<>());
            p.setPages(1l);
        }

        //查询详细信息
        List<Long> likeList = new ArrayList<>(set);
        Map<Long, UserInfo> ids = userInfoApi.findByIds(likeList, null);
        LovesVo vo = null;
        for (Comment comment : commentList) {
            UserInfo userInfo = ids.get(comment.getUserId());
            if (userInfo != null){
                vo = new LovesVo();
                vo.setId(userInfo.getId() + "");
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd kk:mm:ss").format(new Date(comment.getCreated())));
                vos.add(vo);
            }
        }
        p.setPage(page);
        p.setPagesize(pagesize);
        p.setCounts(Long.valueOf(vos.size()));
        p.setPages(Long.valueOf(vos.size() / pagesize));
        p.setItems(vos);
        return p;
    }

    //公告列表
    public PageResult announcements(Integer page, Integer pagesize) {
        PageResult p = new PageResult();
        List<Announcement> list = announcementApi.page(page, pagesize);
        List<AnnouncementsVo> anns = new ArrayList<>();
        AnnouncementsVo a = null;
        if (list != null && list.size() > 0){
            for (Announcement ann : list) {
                a = new AnnouncementsVo();
                a.setId(ann.getId() + "");
                a.setTitle(ann.getTitle());
                a.setCreateDate(new SimpleDateFormat("yyyy-MM-dd kk:mm:ss").format(ann.getCreated()));
                a.setDescription(ann.getDescription());
                anns.add(a);
            }
            p.setPage(page);
            p.setPagesize(pagesize);
            p.setCounts(Long.valueOf(list.size()));
            p.setPages(Long.valueOf(p.getCounts() / pagesize));
            p.setItems(anns);
            return p;
        }

        p.setPage(page);
        p.setPagesize(pagesize);
        p.setCounts(0l);
        p.setPages(1l);
        p.setItems(new ArrayList<>());

        return p;
    }
}
